home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: How to pass function as arg?
- Date: Sun, 21 Apr 96 12:04:21 GMT
- Organization: none
- Message-ID: <830088261snz@genesis.demon.co.uk>
- References: <317937f7.325108@news.csus.edu>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <317937f7.325108@news.csus.edu> wleong@sfsu.edu "Jerry Leong" writes:
-
- >Please don't flame me for asking this question as I have read the faq,
- >the newsgroup & I still couldn't find a satisfying answer.
- >
- >I couldn't quite figure out how to do this. Below is the pseudo-code :
- >
- >void do_something(void)
- >{
- >}
- >
- >void call_this(void func)
-
- func need to be a pointer to a function, not simple void (void is not a
- valid type for any object). Use:
-
- void call_this(void (*func)(void))
-
- As a function parameter you are allowed to write this more simply as:
-
- void call_this(void func(void))
-
- but many people prefer the longer form for consistency and to show the
- pointer nature explicitly.
-
- >{
- > func();
-
- Similarly some prefer the longer form to show a pointer is being dereferenced:
-
- (*func)();
-
- >}
- >
- >main()
-
- This form is valid but obsolete. Better style is:
-
- int main(void)
-
- >{
- > void (*fp)() = do_something();
-
- do_somthing() *calls* function do_something. You just want a pointer to it
- i.e.
-
- void (*fp)(void) = do_something;
-
- If you prefer you can write the equivalent:
-
- void (*fp)(void) = &do_something;
-
- > call_this(fp);
-
- return 0;
-
- >}
-
- ...
-
- >p/s: Could this be another good topic for FAQ??
-
- I'm not convinced that is meets the "Frequently Asked" criterion.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-